{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e52af24e",
   "metadata": {},
   "source": [
    "### Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "fdeea0fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import warnings\n",
    "from tqdm import tqdm\n",
    "from torch.autograd import Variable\n",
    "from sklearn.metrics import mean_absolute_error"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f064887f",
   "metadata": {},
   "source": [
    "### Auglichem imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a6bcf959",
   "metadata": {},
   "outputs": [],
   "source": [
    "from auglichem.crystal import RotationTransformation, SupercellTransformation\n",
    "from auglichem.crystal.data import CrystalDatasetWrapper\n",
    "from auglichem.crystal.models import GINet, GCN"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7125df85",
   "metadata": {},
   "source": [
    "### Set up dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2887799f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading data to: ./data_download/HOIP...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "130it [00:00, 251.67it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting zipfile...\n",
      "Removing zipfile...\n"
     ]
    }
   ],
   "source": [
    "# Create transformation\n",
    "transform = [\n",
    "    SupercellTransformation(),\n",
    "]\n",
    "\n",
    "# Initialize dataset object\n",
    "dataset = CrystalDatasetWrapper(\"HOIP\", batch_size=128, kfolds=4,\n",
    "                                valid_size=0.1, test_size=0.1)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e818fdf",
   "metadata": {},
   "source": [
    "### Train the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2855ac6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def train(model, train_loader):\n",
    "    with warnings.catch_warnings():\n",
    "        warnings.simplefilter(\"ignore\")\n",
    "        for epoch in range(1):\n",
    "            for bn, data in tqdm(enumerate(train_loader)):        \n",
    "                optimizer.zero_grad()\n",
    "\n",
    "                pred = model(data)\n",
    "                loss = criterion(pred, data.y)\n",
    "\n",
    "                loss.backward()\n",
    "                optimizer.step()\n",
    "    return model"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "772cfea1",
   "metadata": {},
   "source": [
    "### Test the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "77baed2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def evaluate(model, test_loader, validation=False):\n",
    "    with warnings.catch_warnings():\n",
    "        warnings.simplefilter(\"ignore\")\n",
    "        with torch.no_grad():\n",
    "            model.eval()\n",
    "            preds = torch.Tensor([])\n",
    "            targets = torch.Tensor([])\n",
    "            for data in test_loader:\n",
    "                pred = model(data)\n",
    "                preds = torch.cat((preds, pred))\n",
    "                targets = torch.cat((targets, data.y))\n",
    "\n",
    "            mae = mean_absolute_error(preds, targets)   \n",
    "        \n",
    "        set_str = \"VALIDATION\" if(validation) else \"TEST\"\n",
    "        print(\"{0} MAE: {1:.3f}\".format(set_str, mae))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "072b1301",
   "metadata": {},
   "source": [
    "### Initialize Model, Train, Test for First Fold"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "1f47e690",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ignoring splitting. Using pre-split k folds.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  0%|                                                                                                           | 0/1346 [00:00<?, ?it/s]/home/mlai/anaconda3/envs/dev_auglichem/lib/python3.8/site-packages/pymatgen/io/cif.py:710: UserWarning: No _symmetry_equiv_pos_as_xyz type key found. Spacegroup from _symmetry_space_group_name_H-M used.\n",
      "  warnings.warn(msg)\n",
      "/home/mlai/anaconda3/envs/dev_auglichem/lib/python3.8/site-packages/pymatgen/io/cif.py:1165: UserWarning: Issues encountered while parsing CIF: No _symmetry_equiv_pos_as_xyz type key found. Spacegroup from _symmetry_space_group_name_H-M used.\n",
      "  warnings.warn(\"Issues encountered while parsing CIF: %s\" % \"\\n\".join(self.warnings))\n",
      "  0%|                                                                                                   | 1/1346 [00:00<02:18,  9.72it/s]/home/mlai/anaconda3/envs/dev_auglichem/lib/python3.8/site-packages/pymatgen/io/cif.py:1165: UserWarning: Issues encountered while parsing CIF: Some fractional co-ordinates rounded to ideal values to avoid issues with finite precision.\n",
      "No _symmetry_equiv_pos_as_xyz type key found. Spacegroup from _symmetry_space_group_name_H-M used.\n",
      "  warnings.warn(\"Issues encountered while parsing CIF: %s\" % \"\\n\".join(self.warnings))\n",
      "100%|███████████████████████████████████████████████████████████████████████████████████████████████| 1346/1346 [00:05<00:00, 240.74it/s]\n",
      "/home/mlai/anaconda3/envs/dev_auglichem/lib/python3.8/site-packages/torch_geometric/deprecation.py:13: UserWarning: 'data.DataLoader' is deprecated, use 'loader.DataLoader' instead\n",
      "  warnings.warn(out)\n",
      "15it [00:10,  1.41it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "VALIDATION MAE: 3.216\n",
      "TEST MAE: 3.085\n"
     ]
    }
   ],
   "source": [
    "# Get model\n",
    "model = GCN() # Note: GCN and GINet are interchangeable in use cases\n",
    "\n",
    "criterion = torch.nn.MSELoss()\n",
    "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)\n",
    "\n",
    "# Get train/valid/test splits as loaders\n",
    "train_loader, valid_loader, test_loader = dataset.get_data_loaders(transform=transform, fold=0)\n",
    "\n",
    "model = train(model, train_loader)\n",
    "\n",
    "evaluate(model, valid_loader, validation=True)\n",
    "evaluate(model, test_loader)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ab44b38",
   "metadata": {},
   "source": [
    "### Training and Testing on Additional Folds\n",
    "\n",
    "This is done by initializing a new model and optimizer, and simply selecting a new fold in `get_data_loaders`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "32f9cf2c",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/mlai/anaconda3/envs/dev_auglichem/lib/python3.8/site-packages/torch_geometric/deprecation.py:13: UserWarning: 'data.DataLoader' is deprecated, use 'loader.DataLoader' instead\n",
      "  warnings.warn(out)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ignoring splitting. Using pre-split k folds.\n",
      "Augmentation has already been done.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "15it [00:09,  1.53it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "VALIDATION MAE: 0.771\n",
      "TEST MAE: 0.688\n"
     ]
    }
   ],
   "source": [
    "# Get model\n",
    "model = GCN() # Note: SchNet and GINet are interchangeable in use cases\n",
    "\n",
    "criterion = torch.nn.MSELoss()\n",
    "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)\n",
    "\n",
    "# Get train/valid/test splits as loaders\n",
    "train_loader, valid_loader, test_loader = dataset.get_data_loaders(transform=transform, fold=1) # New fold\n",
    "\n",
    "model = train(model, train_loader)\n",
    "\n",
    "evaluate(model, valid_loader, validation=True)\n",
    "evaluate(model, test_loader)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "75f33381",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/mlai/anaconda3/envs/dev_auglichem/lib/python3.8/site-packages/torch_geometric/deprecation.py:13: UserWarning: 'data.DataLoader' is deprecated, use 'loader.DataLoader' instead\n",
      "  warnings.warn(out)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ignoring splitting. Using pre-split k folds.\n",
      "Augmentation has already been done.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "15it [00:08,  1.83it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "VALIDATION MAE: 1.638\n",
      "TEST MAE: 1.699\n"
     ]
    }
   ],
   "source": [
    "# Get model\n",
    "model = GCN() # Note: SchNet and GINet are interchangeable in use cases\n",
    "\n",
    "criterion = torch.nn.MSELoss()\n",
    "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)\n",
    "\n",
    "# Get train/valid/test splits as loaders\n",
    "train_loader, valid_loader, test_loader = dataset.get_data_loaders(transform=transform, fold=2)\n",
    "\n",
    "model = train(model, train_loader)\n",
    "\n",
    "evaluate(model, valid_loader, validation=True)\n",
    "evaluate(model, test_loader)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "35c0df8d",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/mlai/anaconda3/envs/dev_auglichem/lib/python3.8/site-packages/torch_geometric/deprecation.py:13: UserWarning: 'data.DataLoader' is deprecated, use 'loader.DataLoader' instead\n",
      "  warnings.warn(out)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ignoring splitting. Using pre-split k folds.\n",
      "Augmentation has already been done.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "15it [00:08,  1.80it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "VALIDATION MAE: 1.960\n",
      "TEST MAE: 1.863\n"
     ]
    }
   ],
   "source": [
    "# Get model\n",
    "model = GCN() # Note: SchNet and GINet are interchangeable in use cases\n",
    "\n",
    "criterion = torch.nn.MSELoss()\n",
    "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)\n",
    "\n",
    "# Get train/valid/test splits as loaders\n",
    "train_loader, valid_loader, test_loader = dataset.get_data_loaders(transform=transform, fold=3)\n",
    "\n",
    "model = train(model, train_loader)\n",
    "\n",
    "evaluate(model, valid_loader, validation=True)\n",
    "evaluate(model, test_loader)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6737cc73",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
